#!/usr/bin/env python
# -*-coding:utf-8-*-
# @Time : 2021/9/23 9:32
# @Author : Li Yan
import os

from flask import current_app
from minio import Minio


def get_folder(uploadtype: str) -> str:
    type_folder = {'image': 'images', 'video': 'video', 'file': 'files'}
    return type_folder[uploadtype]


def save2minio(lock: object, app: object, uploadtype: str, file_name: str, date_format: str) -> None:
    lock.acquire()
    folder = get_folder(uploadtype)

    filebyupload = '/'.join([folder, date_format, file_name])
    with app.app_context():
        file_path = os.path.join(os.getcwd(), current_app.config['TMP_FOLDER'], file_name)
        client = Minio(
            current_app.config['MINIO_ENDPOINT'],
            access_key=current_app.config['MINIO_ACCESS_KEY'],
            secret_key=current_app.config['MINIO_SECRET_KEY'],
            secure=current_app.config['MINIO_SECURE']
        )
        client.fput_object(
            current_app.config['BUCKET'], filebyupload, file_path
        )
    os.remove(file_path)
    lock.release()
